// 格式化日期
export function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 格式化时间（仅时间部分）
export function formatTime(date) {
  const d = new Date(date)
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}

// 格式化日期时间（特定格式）
export function formatDateTime(date) {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化数字（添加千分位）
export function formatNumber(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 防抖函数
export function debounce(fn, wait) {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }
}

// 节流函数
export function throttle(fn, delay) {
  let lastCall = 0
  return function(...args) {
    const now = new Date().getTime()
    if (now - lastCall < delay) {
      return
    }
    lastCall = now
    return fn.apply(this, args)
  }
}

// 获取URL参数
export function getQueryParam(name) {
  const url = window.location.href
  const regex = new RegExp(`[?&]${name}=([^&#]*)`)
  const results = regex.exec(url)
  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
}

// 深拷贝
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime())
  }
  if (obj instanceof Array) {
    const cloneArr = []
    for (let i = 0; i < obj.length; i++) {
      cloneArr[i] = deepClone(obj[i])
    }
    return cloneArr
  }
  if (obj instanceof Object) {
    const cloneObj = {}
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        cloneObj[key] = deepClone(obj[key])
      }
    }
    return cloneObj
  }
}

// 判断是否为空对象
export function isEmptyObject(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object
}

// 生成唯一ID
export function generateUniqueId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 截断文本
export function truncateText(text, maxLength) {
  if (!text || text.length <= maxLength) {
    return text
  }
  return text.substring(0, maxLength) + '...'
}

// 校验邮箱格式
export function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return re.test(email)
}

// 校验手机号格式（中国大陆）
export function validatePhone(phone) {
  const re = /^1[3-9]\d{9}$/
  return re.test(phone)
}

// 获取文件扩展名
export function getFileExtension(filename) {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}

// 转换文件大小
export function formatFileSize(bytes) {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 计算剩余时间
export function getTimeRemaining(endTime) {
  const total = new Date(endTime) - new Date()
  const days = Math.floor(total / (1000 * 60 * 60 * 24))
  const hours = Math.floor((total % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((total % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((total % (1000 * 60)) / 1000)

  return {
    total,
    days,
    hours,
    minutes,
    seconds
  }
}

// 活动状态映射
// 前端状态字符串到后端状态整数的映射
export const activityStatusMap = {
  'DRAFT': 0,      // 草稿
  'PENDING': 1,    // 待审核
  'REVIEWED': 2,   // 已审核
  'PUBLISHED': 3,  // 已发布
  'ONGOING': 4,    // 进行中
  'ENDED': 5,      // 已结束
  'CANCELLED': 6   // 已取消
}

// 后端状态整数到前端状态字符串的映射
export const activityStatusReverseMap = {
  0: 'DRAFT',      // 草稿
  1: 'PENDING',    // 待审核
  2: 'REVIEWED',   // 已审核
  3: 'PUBLISHED',  // 已发布
  4: 'ONGOING',    // 进行中
  5: 'ENDED',      // 已结束
  6: 'CANCELLED'   // 已取消
}

// 将前端状态字符串转换为后端状态整数
export function mapStatusToBackend(status) {
  return activityStatusMap[status] !== undefined ? activityStatusMap[status] : 0
}

// 将后端状态整数转换为前端状态字符串
export function mapStatusToFrontend(status) {
  return activityStatusReverseMap[status] !== undefined ? activityStatusReverseMap[status] : 'DRAFT'
}